using System;
using Minesweeper;
using Minesweeper.GUI.HUD.Campsite;
using UnityEngine;

[RequireComponent(typeof(Renderer))]
public abstract class InteractiveObject : MonoBehaviour
{
    private InteractResponser _responser;
    private bool _responserSpawned;
    
    private Renderer _renderer;
    private Material _recentMaterial;
    private Material _highlightMaterial;

    private void Start()
    {
        _renderer = GetComponent<Renderer>();
        _recentMaterial = _renderer.material;
        _highlightMaterial = Resources.Load<Material>("Minesweeper/Materials/Glow Outline");
    }

    private void OnMouseEnter()
    {
        if (!Interactable(CampsitePlayer.Instance)) return;
        _responser = InteractResponser.Create(this);
        _responserSpawned = true;
        _renderer.material = _highlightMaterial;
    }

    private void OnMouseOver()
    {
        if (!_responserSpawned || Interactable(CampsitePlayer.Instance)) return;
        _responser.HideDestroy();
        _responserSpawned = false;
        _renderer.material = _recentMaterial;
    }

    private void OnMouseDown()
    {
        if (!Interactable(CampsitePlayer.Instance)) return;
        if (Interact(CampsitePlayer.Instance)) return;
        _responser.HideDestroy();
        _responserSpawned = false;
        _renderer.material = _recentMaterial;
    }

    private void OnMouseExit()
    {
        if (!_responserSpawned) return;
        _responser.HideDestroy();
        _responserSpawned = false;
        _renderer.material = _recentMaterial;
    }

    public bool Interactable(CampsitePlayer player) => InteractableInternal(player);
    protected virtual bool InteractableInternal(CampsitePlayer player) => true;

    /// <summary>
    /// 当与物体交互时执行
    /// </summary>
    /// <param name="player">交互的玩家</param>
    public abstract bool Interact(CampsitePlayer player);
}
